package org.mags.rema.model.commons;

import java.io.Serializable;
import java.util.Date;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

public class AuditInterceptor extends EmptyInterceptor {	
	public String getUserName() {
		return "mgaitan";
	}
	@Override
	public boolean onFlushDirty(Object object, Serializable id, Object[] currentState,
			Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
		for(int i=0;i<=propertyNames.length-1;i++) {
			if(propertyNames[i].equalsIgnoreCase("updatedBy"))
				currentState[i] = getUserName();
			else
			if(propertyNames[i].equalsIgnoreCase("changeDate"))
				currentState[i] = new Date();
		}
		return true;
	}

	@Override
	public boolean onSave(Object object, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) throws CallbackException {
		for(int i=0;i<=propertyNames.length-1;i++) {
			if(propertyNames[i].equalsIgnoreCase("createdBy"))
				state[i] = getUserName();
			else
			if(propertyNames[i].equalsIgnoreCase("updatedBy"))
				state[i] = getUserName();
			else
			if(propertyNames[i].equalsIgnoreCase("creationDate"))
				state[i] = new Date();
			else
			if(propertyNames[i].equalsIgnoreCase("changeDate"))
				state[i] = new Date();
		}		
		return true;
	}

}
